source("gene_count_module.R")
Enriched_markers_module_UI<-function(id)
{
  ns<-NS(id)
  tagList(
    br(),
    br(),
    fluidRow(column(10,DT::dataTableOutput(ns("TF_genes")))),
    br(),
    hr(),
    radioButtons(ns("lfc_TF"), "Show log2 foldchange?:", choices = c("Yes", "No"),selected = "No"),
    br(),
    fluidRow(
      column(1,
             selectInput(ns("datachoice5")  ,label = h5("Select Data Type"), 
                         choices = list("Excel" = 1, "CSV" = 2),
                         selected = 1)),
      column(1, 
             br(),
             br(),
             downloadButton(ns('download_DE_TF_Table'), 'Download List of Transcription Factors'))),
    #downloadButton(ns('download_DE_TF_Table'), 'Download full Data'),
    DT::dataTableOutput(ns("filtered_TF")),
    br(),
    br(),
    gene_count_module_UI(ns("module3"))
    # uiOutput(ns("plot_option_gene_TF"),
    # downloadButton(ns('download_gene_tf'), 'Download plot'),
    # plotOutput(ns("gene_plot_TF"))
  
  )
}




#Transcription factor
#Compute the Transcription factor based on a list for a list of DE genes
#Construct  a matrix where row->comparison A vs B, C vs D .etc
# columns (up regulated genes, down regulated genes, all DE genes)
#Loop through a similar matrix generated by reactive DE_genes)
#Filter TF for each element in the matrix generated by reactive DE_genes

Enriched_markers_module<-function(input,output,session,TF_list,organism,
                                  DE_genes,combination,wgcna_output,
                                  conchoice,normal,dds.fc,batch_choice,
                                  batch_corrected,anova_table,dds)
{
  combo<-combination()
  num<-length(combo())
  DE_TF<-reactive({
    #TF_list<-input_file(input$TF_file)
     print(head(TF_list()))
    result_DE<-DE_genes()
    
    
    if(!is.null(wgcna_output()))
    {
      if((length(wgcna_output()$modules())>0))
      {
        mod<-wgcna_output()$modules()
        WGCNA_matrix<-wgcna_output()$WGCNA_matrix()
        combo<-combination()
        num<-length(combo())
        Enriched_trasncription_factors(TF_list(),result_DE(),num,organism(),mod,WGCNA_matrix,
                                       anova_table(),conchoice,dds())
      }
    }
    else
    {
      combo<-combination()
      num<-length(combo())
      Enriched_trasncription_factors(TF_list(),result_DE(),num,organism(),NULL,NULL,NULL,NULL,NULL)
    }
   
    
  })
  
  #display summary of TF
  output$TF_genes <- DT::renderDataTable({
    
    result<-DE_TF()
    print("tf")
    print(result)
    
    rows<-num
    modules<-NULL
    
    res<-NULL#data.frame(matrix(NA, nrow = num, ncol = 3))
    
    if(!is.null(wgcna_output()))
    {
      if((length(wgcna_output()$modules())>0))
      {
        modules<-as.data.frame(table(wgcna_output()$modules()))
        
        entry<-c(as.vector(combo()), as.vector(modules$Var1))
        # print(modules$Var1)
        print(entry)
        rows<-length(entry)
        res<-data.frame(matrix(NA, nrow = rows, ncol = 3))
        colnames(res)<-c('Up regulated','Down regulated','Both')
        
        
        print(modules$Var1)
        print(entry)
        rownames(res)<-lapply(1:rows, function(i) {
          unlist(entry[i])
          
        })
        for(i in 1:length(combo()))
        {
          #print(nrow(as.data.frame(result[[i]][1])))
          res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
          res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
          res[i,3]<-nrow(as.data.frame(result[[i]][[3]]))
        }
        for(i in 1+length(combo()):nrow(modules))
        {
          #print(nrow(as.data.frame(result[[i]][1])))
          print('res')
          print(result[[i]][[3]])
          res[i,1:2]<-0
          res[i,3]<-0
          if(!identical(result[[i]][[3]], character(0))) res[i,3]<-length(result[[i]][[3]])
        }
      }
    }
    else{
      res<-data.frame(matrix(NA, nrow = length(combo()), ncol = 3))
      rownames(res)<-lapply(1:length(combo()), function(i) {
        combo()[[i]]
        
      })
      colnames(res)<-c('Up regulated','Down regulated','Both')
      for(i in 1:length(combo()))
      {
        #print(nrow(as.data.frame(result[[i]][1])))
        res[i,1]<-nrow(as.data.frame(result[[i]][1]))
        res[i,2]<-nrow(as.data.frame(result[[i]][2]))
        res[i,3]<-nrow(as.data.frame(result[[i]][3]))
      }
    }
    print(res)
    DT::datatable(res,class = 'cell-border stripe',
                  selection = list(mode='single',target = 'cell'),
                  extensions = list('Scroller'=NULL,'Buttons'=NULL),
                  options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                 buttons = list('copy', list(extend = 'collection',buttons = c('csv', 'excel', 'pdf'),
                                                             text = 'Download table'))),#I('colvis')
                  
                  escape = FALSE
    )
    
  })
  
  observeEvent(input$TF_genes_cell_clicked,{
    print('hey')
    print(input$TF_genes_cells_selected)
    print(input$TF_genes_cell_clicked)
    selected <- input$TF_genes_cells_selected
    row<-selected[1]
    print('row')
    print(row)
    col<-selected[2]
    print('col')
    print(col)
    print(length(selected))
    if(length(selected)>0){
      #Display list of selected transcription factors 
      output$filtered_TF <- DT::renderDataTable({
        print('hey')
        result<-DE_TF()
        if(!is.null(wgcna_output()))
        {
          if((length(wgcna_output()$modules())>0))#input$combination))
          {
            if(row>length(combo())){
            
              gene_list<-  as.data.frame(character())
            if(col==3) gene_list<-result[[row]][[4]]
            else gene_list<-result[[row]][[col]]
            #if(identical(character(0),gene_list)) gene_list<-character()
            
            DT::datatable(gene_list,class = 'cell-border stripe',
                          selection = list(mode='single',target = 'row'),
                          extensions = list('Scroller'=NULL,'Buttons'=NULL),
                          options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                         buttons = list('copy' )))
            }
            else if(row<=length(combo()))
              {
              df<-as.data.frame(result[[row]][[col]])
              print("df")
              print(head(df))
              # genes<-df[,1]
              # df<-df[-1]
              # rownames(df)<-genes
              df_final<- df[order(df$padj),]
              colnames(df_final)[1]<-"Overall mean"
              for (i in 8:length(colnames(df_final)))
              {
                colnames(df_final)[i]<-paste(colnames(df_final)[i],"mean")
              }
              a_tab<-df_final[,-4]
              df_TF=NULL
              if(input$lfc_TF =="No")
              {
                names<-colnames(a_tab)
                df_TF=a_tab[,-3]
              }
              else df_TF=a_tab
              DT::datatable(df_TF,class = 'cell-border stripe',
                            selection = list(mode='single',target = 'row'),
                            extensions = list('Scroller'=NULL,'Buttons'=NULL),
                            options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                           buttons = list('copy')))
            }
              }
          
        }
        else {
          df<-as.data.frame(result[[row]][[col]])
          print("df")
          print(head(df))
          # genes<-df[,1]
          # df<-df[-1]
          # rownames(df)<-genes
          df_final<- df[order(df$padj),]
          colnames(df_final)[1]<-"Overall mean"
          for (i in 8:length(colnames(df_final)))
          {
            colnames(df_final)[i]<-paste(colnames(df_final)[i],"mean")
          }
          a_tab<-df_final[,-4]
          df_TF=NULL
          if(input$lfc_TF =="No")
          {
            names<-colnames(a_tab)
            df_TF=a_tab[,-3]
          }
          else df_TF=a_tab
          DT::datatable(df_TF,class = 'cell-border stripe',
                        selection = list(mode='single',target = 'row'),
                        extensions = list('Scroller'=NULL,'Buttons'=NULL),
                        options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                       buttons = list('copy')))
        }
        
      })
      ###plotcounts of gene
      #disply boxplot for the marker gene selected in the marker gene table
      observeEvent(input$filtered_TF_rows_selected,{
        #get which gene was clicked
        #get the row  number of the gene clicked
        print('hey')
        print(input$filtered_TF_rows_selected)
        #print(input$ANOVA_rows_clicked)
        selected_row <- input$filtered_TF_rows_selected
        print(selected_row)
        #get the normalized data
        full_data<-normal()
        print(head(full_data))
        print('hey')
        #get the DE table where we clicked the gene
        print(input$TF_genes_cells_selected)
        print(input$TF_genes_cell_clicked)
        selected <- input$TF_genes_cells_selected
        row<-selected[1]
        print('row')
        print(row)
        col<-selected[2]
        print('col')
        print(col)
        if(length(selected)>0)
        {
          print('hey')
          #get the table where we clicked the TF
          result<-DE_TF()
          df<-NULL
          df_final<-NULL
          print("gene")
          if(row<=length(input$combination))
          {
            df<-as.data.frame(result[[row]][[col]])
            df_final<- df[order(df$padj),]
            print(head(df_final))
            print("gene")
          }
          else if(row>length(input$combination))
          {
            df_final<-result[[row]][[4]]
          }
          # genes<-df[,1]
          # df<-df[-1]
          # rownames(df)<-genes
          #get the gene
          an_gene<-rownames(df_final)[selected_row]
          #an_gene<-df_final[selected_row,1]
          print(an_gene)
          counts<-as.vector(full_data[which(an_gene %in% rownames(full_data)),])
          #print(counts)
          #print(as.factor(colData(dds.fc()[[1]])[,as.numeric(input$conchoice)]))
          cond<-as.vector(colData(dds.fc()[[1]])[,as.numeric(conchoice)])
          #rownames(cond)<-colData(dds.fc()[[1]])[,1]
          library('data.table')
          print(length(counts))
          print(length(cond))
          df<-data.frame(counts,cond)
          colnames(df)<-c('count','condition')
          print(head(df))
          print(batch_choice())
          print(as.numeric(batch_choice()))
          batch<-batch_choice()
          if(as.numeric(batch)==1) callModule(gene_count_module,"module3",NULL,reactive({dds.fc()[[1]]}),reactive({an_gene}))
          else 
            {
              idx<-which(rownames(batch_corrected()) %in% an_gene)
              print(idx)
              callModule(gene_count_module,"module3",batch_corrected()[idx,],reactive({dds.fc()[[1]]}),reactive({an_gene}))
            }
        }
      })
      #download Transcription factors
      output$download_DE_TF_Table <- downloadHandler(
        
        filename = function(){ 
        
          if (as.numeric(input$datachoice5==1))  
          {
          #condition<-paste(combina]tion()[[row]][1],' vs ',combination()[[row]][2])
          if(row<=length(input$combination))
          {
          condition<-combo()[[row]]
          if(col==1) paste('Up regulated TF for ',condition,'.xlsx')
          else if(col==2) paste('Down regulated TF for ',condition,'.xlsx')
          else paste('All DE TF for ',condition,'.xlsx')
          }
          else{
            mod<-wgcna_output()$modules()
            modules<-as.data.frame(table(mod))
            colnames(modules)<-c("Var1","number")
            paste('ANOVA table for TF in module ',modules$Var1[row],'.xlsx')
          }
          #paste("DE genes for condition ",input$condition1," vs ",input$condition2,'.csv')
        }
        else {
          #condition<-paste(combina]tion()[[row]][1],' vs ',combination()[[row]][2])
          if(row<=length(input$combination))
          {
            condition<-combo()[[row]]
            if(col==1) paste('Up regulated TF for ',condition,'.csv')
            else if(col==2) paste('Down regulated TF for ',condition,'.csv')
            else paste('All DE TF for ',condition,'.csv')
          }
          else{
            mod<-wgcna_output()$modules()
            modules<-as.data.frame(table(mod))
            colnames(modules)<-c("Var1","number")
            paste('ANOVA table for TF in module ',modules$Var1[row],'.csv')
          }
        }},
          
        
        
        content = function(file) {
          if (as.numeric(input$datachoice5==1)){  
          #sort by adjusted p value.
          print('heyho')
          result<-DE_TF()
          df_final<-as.data.frame(character(0))
          nam<-"Sheet1"
          if(row<=length(input$combination))
          {
          df<-as.data.frame(result[[row]][[col]])
          df_final<- df[order(df$padj),]
          colnames(df_final)[1]<-"Overall mean"
          for (i in 8:length(colnames(df_final)))
          {
            colnames(df_final)[i]<-paste(colnames(df_final)[i],"mean")
          }
          nam<-"Sheet 1"
          condition<-combo()[[row]]
          condition<-str_replace_all(condition,"[^[:alnum:]]",".")
          if(col==1) nam<-paste('Up regulated TF for ',condition)
          else if(col==2) nam<-paste('Down regulated TF for ',condition)
          else nam<-paste('All DE TF for ',condition)
          }
          else{
            df_final<-result[[row]][[4]]
            mod<-wgcna_output()$modules()
            modules<-as.data.frame(table(mod))
            colnames(modules)<-c("Var1","number")
            nam<-paste('ANOVA table for TF in module ',modules$Var1[row])
          }
          M <- as.matrix(df_final)
          wb <- createWorkbook()
          addWorksheet(wb, sheetName = "TF table")
          writeData(wb = wb, sheet = 1, x = M, colNames = T, rowNames = T)
          saveWorkbook(wb, file)
         # write.xlsx2(df_final, file, sheetName = nam,
        #              col.names = TRUE, row.names = TRUE, append = FALSE)
        }
          else{
            result<-DE_TF()
            df_final<-as.data.frame(character(0))
            nam<-"Sheet1"
            if(row<=length(input$combination))
            {
              df<-as.data.frame(result[[row]][[col]])
              df_final<- df[order(df$padj),]
              colnames(df_final)[1]<-"Overall mean"
              for (i in 8:length(colnames(df_final)))
              {
                colnames(df_final)[i]<-paste(colnames(df_final)[i],"mean")
              }
              nam<-"Sheet 1"
              condition<-combo()[[row]]
              condition<-str_replace_all(condition,"[^[:alnum:]]",".")
              if(col==1) nam<-paste('Up regulated TF for ',condition)
              else if(col==2) nam<-paste('Down regulated TF for ',condition)
              else nam<-paste('All DE TF for ',condition)
            }
            else{
              df_final<-result[[row]][[4]]
              mod<-wgcna_output()$modules()
              modules<-as.data.frame(table(mod))
              colnames(modules)<-c("Var1","number")
              nam<-paste('ANOVA table for TF in module ',modules$Var1[row])
            }
            write.csv(df_final, file)
            
          }
        }
      )
    }
  })
  return(list(de_genes=reactive({DE_TF()})))
}
